package com.ruoyi.system.util;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author lixbin
 * @ClassName NetUtil
 * @description: TODO
 * @datetime 2024年 12月 27日 16:22
 * @version: 1.0
 */
public class NetUtil {
    public static void downloadFile(String urlPath, String localPath) throws Exception {
        URL url = new URL(urlPath);
        URLConnection connection = url.openConnection();

        File file = new File(localPath);
        file.getParentFile().mkdirs();
        file.createNewFile();

        try (FileOutputStream fs = new FileOutputStream(localPath)) {
            try (InputStream inputStream = connection.getInputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, len);
                }
            }
        }
    }

    public static void downloadFile(String urlPath, HttpServletResponse response) throws Exception {
        URL url = new URL(urlPath);
        URLConnection connection = url.openConnection();
        try (InputStream inputStream = connection.getInputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, len);
            }
        }
    }
}
